#!/usr/bin/python2.6

import cgitb # TODO: Remove before launching RBK.
import cgi, os, sys
from os import path

DIRECTORY_INDEX = 'top_rbks.py'
TEMPLATE_EXTENSION = 'html'
TEMPLATE_FILE_PATH = 'template.' + TEMPLATE_EXTENSION

def serve_page(page_title):
    ''''''
    cgitb.enable() # TODO: Remove before launching RBK.
    absolute_file_path = os.environ['SCRIPT_FILENAME']
    relative_file_path_index = absolute_file_path.index('kurtvl/cgi-bin/')
    relative_file_path = absolute_file_path[relative_file_path_index:]
    if relative_file_path.endswith(DIRECTORY_INDEX):
        relative_file_path = path.dirname(relative_file_path) + '/'
    expected_uri = 'https://' + os.environ['SERVER_NAME'] + '/~' + \
        relative_file_path
    
    if os.environ['SCRIPT_URI'] != expected_uri:
        query_string = os.environ['QUERY_STRING']
        if query_string != '':
            query_string = '?' + query_string
        expected_uri_with_query_string = expected_uri + query_string
        print("Location: {0}\n".format(expected_uri_with_query_string))
        sys.exit(0)
    
    print("Content-Type: text/html\n")
    template = _load_as_str(TEMPLATE_FILE_PATH)
    contents_file_path = _replace_extension(absolute_file_path,
                                            TEMPLATE_EXTENSION)
    contents = _load_as_str(contents_file_path)
    print(template.format(page_title, contents))

def _test_serve_page():
    pass

def _load_as_str(input_file_path):
    '''Return the contents of the file at the given file path as a str.

    Raise IOError if the file does not exist or could not be read.
    
    input_file_path is a str.
    '''
    input_stream = open(input_file_path)
    file_as_str = input_stream.read()
    input_stream.close()
    return file_as_str

def _test_load_as_str():
    pass

def _replace_extension(file_path, new_extension):
    '''Replace the last extension of the given file path with new_extension.
    
    Assume file path ends in a filename with an extension. Raise ValueError if
    file_path lacks a period.
    
    file_path and new_extension are both of type str.
    '''
    extension_index = file_path.rindex('.') + 1
    file_path_sans_extension = file_path[:extension_index]
    return file_path_sans_extension + new_extension

def _test_replace_extension():
    assert(_replace_extension('I am a relative file path.py', 'png') == \
           'I am a relative file path.png')
    assert(_replace_extension('//I/am/an//absolute///file//path.txt', 'bat') \
           == '//I/am/an//absolute///file//path.bat')
    assert(_replace_extension('I have an empty extension.', 'webarchive') == \
           'I have an empty extension.webarchive')
    try:
        _replace_extension('I lack an extension', 'gif')
    except ValueError:
        pass
    else:
        assert('Function _replace_extension should have raised ValueError.')

def _run_tests():
    _test_load_as_str()
    _test_replace_extension()
    _test_serve_page()

if __name__ == '__main__':
    _run_tests()
